<?php

namespace Biz\model\activity;

use Biz\cache\Sku as cSku;
use Biz\service\activity\AllActivityInfo;
use Doraemon\pockets\datebase\BaseDbModel;

class LimitTimeRobbingSku extends BaseDbModel
{
    const _CONFIG_FILE_ = 'db_shop';

    const _CONFIG_SELECT_ = 'db_activity';

    const _DATABASE_ = 'shop_activity';

    const _TABLE_NAME = 'limit_time_robbing_sku';


    const STATUS_NORMAL = 1;


    const STATUS_DEL = 9;


    public static function getInfo($where)
    {
        if (!isset($where['status'])) {
            $where['status'] = self::STATUS_NORMAL;
        }

        return self::select("*", $where);

    }

    public static function getInfoBySkuIds($sku_ids, $where = [])
    {
        if (!isset($where['status'])) {
            $where['status'] = self::STATUS_NORMAL;
        }

        $where = array_merge(['sku_id' => $sku_ids], $where);

        $infos = self::select("*", $where);


        $robbing_ids = array_column($infos, "robbing_id");
        $robbingInfos = LimitTimeRobbing::getInfos($robbing_ids);
        $infos = array_map(function ($info) use ($robbingInfos) {

            if (isset($robbingInfos[$info['robbing_id']])) {
                $info['id'] = $info['robbing_id'];
                $info['promo_price'] = $robbingInfos[$info['robbing_id']]['buy_price'];
                $info['promo_limit'] = $robbingInfos[$info['robbing_id']]['buy_limit'];
                $info['commission_ratio'] = $robbingInfos[$info['robbing_id']]['commission'];
                return $info;
            } else {
                return [];
            }

        }, $infos);

        return array_column(array_filter($infos), null, 'sku_id');

    }


    public static function setMutiStock($currStocks)
    {
        $currentTime = date("Y-m-d H:i:s");

//        $query = 'UPDATE ' . self::_TABLE_NAME . ' SET promo_stock  = CASE sku_id ';
        foreach ($currStocks as $sku_id => $stock) {
            self::update([
                'promo_stock' => $stock,
            ], [
                'sku_id' => $sku_id,
                'start_time[<]' => $currentTime,
                'end_time[>]' => $currentTime,
            ]);
//            $query .= sprintf(" WHEN %d THEN %d ", $sku_id, $stock);
        }
//        $query .= " END WHERE  sku_id IN (" . implode(", ", array_keys($currStocks)) . ") AND start_time < '" . $currentTime . "' AND end_time > '" . $currentTime . "'";


//        return self::query($query);


    }


    public static function saveRobingInfo(
        $start_time,
        $end_time,
        $robbing_id,
        $goods_id,
        $shop_id,
        $admin_id,
        $sku_stocks
    ) {
        $currSkus = self::selectSkus($robbing_id, array_keys($sku_stocks));

        foreach ($sku_stocks as $sku_id => $stock) {
            if ($stock) {
                if (isset($currSkus[$sku_id])) {
                    self::update([
                        'promo_stock' => $stock,
                        'start_stock' => $stock,
                        'edittime' => date("Y-m-d H:i:s"),
                        'action_uid' => $admin_id,
                    ], [
                        'robbing_id' => $robbing_id,
                        'sku_id' => $sku_id,
                    ]);
                } else {

                    self::insert([
                        'robbing_id' => $robbing_id,
                        'shop_id' => $shop_id,
                        'goods_id' => $goods_id,
                        'sku_id' => $sku_id,
                        'promo_stock' => $stock,
                        'start_stock' => $stock,
                        'start_time' => $start_time,
                        'end_time' => $end_time,
                        'addtime' => date("Y-m-d H:i:s"),
                        'edittime' => date("Y-m-d H:i:s"),
                        'action_uid' => $admin_id,
                        'status' => self::STATUS_NORMAL

                    ]);

                }

            } else {
                self::update(['status' => self::STATUS_DEL], [
                    'robbing_id' => $robbing_id,
                    'sku_id' => $sku_id
                ]);
                AllActivityInfo::admDelActivityBySkuId($robbing_id,AllActivityInfo::ACTIVITY_TYPE_LIMIT_TIME_ROB, $goods_id,$sku_id,AllActivityInfo::ALL_ACTIVITY_TYPE_FLASH_SALE);
            }
        }


    }

    private static function selectSkus($rob_id, $sku_ids)
    {
        $skus = self::select("*", [
            'robbing_id' => $rob_id,
            'sku_id' => $sku_ids,
            'status' => self::STATUS_NORMAL
        ]);

        return array_column($skus, null, 'sku_id');
    }

    public static function getInfosByRobID($robbing_ids, $is_has_stock = false, $isMaster = false)
    {
        $map = [];
        $map['robbing_id'] = $robbing_ids;
        if ($is_has_stock) {
            $map['promo_stock[>]'] = 0;
        }
        $map['status'] = self::STATUS_NORMAL;
        $funName = 'select';
        if ($isMaster) {
			$funName = 'select_master';
		}

        $robInfos = self::$funName("*", $map);

        $rst = [];
        foreach ($robInfos as $robInfo) {
            $rst[$robInfo['robbing_id']][] = $robInfo;
        }

        return $rst;
    }

    public static function getStockByRobid($robbing_id)
    {
        $infos = self::select("*", [
            'robbing_id' => $robbing_id,
            'status' => self::STATUS_NORMAL
        ]);

        return array_sum(array_column($infos, 'promo_stock'));

    }

    public static function getSkuInfosByGoodsId($goodsIds)
    {
        $infos = self::select("*", [
            'goods_id' => $goodsIds,
            'end_time[>]' => date('Y-m-d H:i:s'),
            'status' => self::STATUS_NORMAL
        ]);
        $formatData = [];
        foreach ($infos as $info) {
            if (!isset($formatData[$info['goods_id']])) {
                $formatData[$info['goods_id']]['expire_time'] = date('Y-m-d H:i:s', time() + cSku::_CACHE_EXPIRE_TIME);
            }
            if ($info['start_time'] < date('Y-m-d H:i:s')) {
                $formatData[$info['goods_id']]['list'][$info['sku_id']] = $info;
                $formatData[$info['goods_id']]['expire_time'] = min($formatData[$info['goods_id']]['expire_time'],
                    $info['end_time']);
            } else {
                $formatData[$info['goods_id']]['expire_time'] = min($formatData[$info['goods_id']]['expire_time'],
                    $info['start_time']);
            }
        }
        return $formatData;
    }

    public static function getInfosByGid($goodsids, $time = '')
    {
        if (!$time) {
            $time = date('Y-m-d H:i:s');
        }
        $infos = self::select("*", [
            'goods_id' => $goodsids,
            'start_time[<]' => $time,
            'end_time[>]' => $time,
            'status' => self::STATUS_NORMAL
        ]);

        $Rst = [];
        foreach ($infos as $info) {
            $Rst[$info['goods_id']][$info['sku_id']] = $info;
        }

        return $Rst;

    }

    public static function getSkuInfoByGoodsIds($goodsIds, $time, $field = '*')
    {
        $infos = self::select($field, [
            'goods_id' => $goodsIds,
            'start_time[>]' => $time,
            'status' => self::STATUS_NORMAL
        ]);

        $result = [];
        foreach ($infos as $info) {
            $result[$info['goods_id']][$info['sku_id']] = $info['sku_id'];
        }

        return $result;
    }

    public static function getSkuInfoByGIds($goodsIds, $time, $field = '*')
    {
        $infos = self::select($field, [
            'goods_id' => $goodsIds,
            'start_time[<]' => $time,
            'end_time[>]' => $time,
            'status' => self::STATUS_NORMAL
        ]);

        $result = [];
        foreach ($infos as $info) {
            $result[$info['goods_id']][$info['sku_id']] = $info['sku_id'];
        }
        return $result;
    }

    public static function admSave($datas, $adminuid)
	{
		foreach ($datas['goods'] as $goods) {
			$currentSkuIds = [];
			foreach ($goods['start_stock'] as $skuId => $skustock) {
				$saveData = [
					'promo_stock' => $skustock,
					'buy_price' => $goods['buy_price'],
					'start_stock' => $skustock,
					'start_time' => $goods['start_time'],
					'end_time' => $goods['end_time'],
					'action_uid' => $adminuid,
					'status' => self::STATUS_NORMAL
				];
				$currentSkuIds[] = $skuId;
				$id = self::get('id', ['robbing_id' => $goods['robbing_id'], 'sku_id' => $skuId]);
				if ($id) {
					$results = self::update(array_merge(['edittime' => date('Y-m-d H:i:s')], $saveData), ['id' => $id]);
				} else {
					$results = self::insert(array_merge([
						'robbing_id' => $goods['robbing_id'],
						'shop_id' => $goods['shop_id'],
						'goods_id' => $goods['goods_id'],
						'sku_id' => $skuId,
						'addtime' => date('Y-m-d H:i:s')], $saveData));
				}
				if (!$results->rowCount()) {
					throw new \Exception('更新数据库失败' . json_encode(self::log(), JSON_UNESCAPED_UNICODE));
				}
			}

			$where = ['robbing_id' => $goods['robbing_id']];
			if ($currentSkuIds) {
				$where['sku_id[!]'] = $currentSkuIds;
			}
			self::update(['status' => self::STATUS_DEL], $where);
		}
	}


}
